package utils

import (
	"fmt"
	"os"
	"strings"
)

// func GetHostname(h string) (string, error) {
// 	hostname, err := os.Hostname()
// 	if err != nil {
// 		log.Println(err)
// 		return "", err
// 	}
// 	return hostname, nil
// }

// GetHostname returns OS's hostname if 'hostnameOverride' is empty; otherwise, it returns
// 'hostnameOverride'. In either case, the value is canonicalized (trimmed and
// lowercased).
func GetHostname(hostnameOverride string) (string, error) {
	hostName := hostnameOverride
	if len(hostName) == 0 {
		nodeName, err := os.Hostname()
		if err != nil {
			return "", fmt.Errorf("couldn't determine hostname: %w", err)
		}
		hostName = nodeName
	}

	// Trim whitespaces first to avoid getting an empty hostname
	// For linux, the hostname is read from file /proc/sys/kernel/hostname directly
	hostName = strings.TrimSpace(hostName)
	if len(hostName) == 0 {
		return "", fmt.Errorf("empty hostname is invalid")
	}

	return strings.ToLower(hostName), nil
}
